package com.yingma.common.controller;


import com.google.code.kaptcha.Producer;
import com.yingma.common.util.AjaxResult;
import com.yingma.common.util.ShiroUtils;
import com.yingma.system.entity.JcSysUser;
import com.yingma.system.service.JcSysUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * (JcSysUser)表控制层
 *
 * @author makejava
 * @since 2020-03-03 16:20:48
 */
@RestController
@RequestMapping("jcSysUser")
public class JcSysUserController {
    /**
     * 服务对象
     */
    @Resource
    private JcSysUserService jcSysUserService;
    @Resource
    private Producer producer;
    @Autowired
    HttpServletRequest requestTest;
    @Autowired
    HttpSession session;
    /**
     * 获取登陆验证码
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "captcha.jpg",method = RequestMethod.GET)
    public void captcha(HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        session = requestTest.getSession();
        // 生成文字验证码
        String text = producer.createText();
        // 生成图片验证码
        BufferedImage image = producer.createImage(text);
        // 保存到验证码到 session
        session.setAttribute("text", text);
        //System.out.println("没有点击登陆之前获取的session id=>"+session.getId());
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.close();
    }
    /**
     * 登陆
     * @param code
     * @param password
     * @param captcha
     * @return
     * @throws IOException
     */
    @ApiOperation("登陆")
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public AjaxResult logins(String code, String password, String captcha,HttpServletRequest request) throws IOException{
       /* code="test";
        password="Jetchain2019";*/
        /*String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if (!captcha.equalsIgnoreCase(kaptcha)) {
            return AjaxResult.error("验证码不正确");
        }*/
        Object kaptcha = session.getAttribute("text");
        if(kaptcha == null){
            System.out.println(1);
            return AjaxResult.error("验证码已失效");
        }
        if(!captcha.equals(kaptcha)){
            return AjaxResult.error("验证码不正确");
        }
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();

        // sha256加密
        password = new Sha256Hash(password).toHex();
//        System.out.println(password);
        //封装用户登陆的数据 放入 token中
        UsernamePasswordToken token = new UsernamePasswordToken(code, password);
        HttpSession session = request.getSession();
        session.setAttribute("token",token);
        session.setMaxInactiveInterval(10000);
        try {
            subject.login(token);            //如果没有异常就说明OK了
            AjaxResult ajax= new AjaxResult();
            ajax.put("token",token);
            System.out.println(ajax);
            return AjaxResult.success("登陆成功");
        } catch (UnknownAccountException e) {
            return AjaxResult.error("账号或密码不正确");
        } catch (IncorrectCredentialsException e) {
            return AjaxResult.error("账号或密码不正确");
        } catch (LockedAccountException e) {
            return AjaxResult.error("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return AjaxResult.error("账户验证失败");
        }
        // 记录登录日志
        // 登录IP   String ipAddress="127.0.0.1";
        /*String ipAddress = GetIpAddress.getIpAddress(request);
        JcSysLoginLog jcSysLoginLog=new JcSysLoginLog();
        jcSysLoginLog.setId("");
        jcSysLoginLog.setIp(ipAddress);
        List<JcSysUser> sysUserList =jcSysUserService.login(code,password);
        if(sysUserList.size()<=0){
            return AjaxResult.error("获取内容失败",sysUserList);
        }*/
    }
    @ApiOperation("获取当前登陆的用户名")
    @RequestMapping(value = "/currentUserName",method = RequestMethod.GET)
    public JcSysUser currentUserName() {
        Subject subject = SecurityUtils.getSubject();
        JcSysUser jcSysUser=(JcSysUser) subject.getPrincipal();
        return jcSysUser;
    }
    /**
     * 退出
     * @return
     */
    @ApiOperation("退出功能")
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "success";
    }









}
